import React, { PureComponent } from 'react';
import { Input, Form, Cascader, Select, Modal, Row, Col, message, InputNumber, TreeSelect, DatePicker, Upload, Button } from 'antd';
import { editPerson, auditPerson, checkRepeatIdCard } from '@/services/peoples'
import { getHandle, upSubjectMember } from '@/services/baseurl'
import Authorized from '@/components/Authorized/Authorized'
import moment from 'moment';
import { isZhengda, isAnte, hasCompany } from '@/utils/utils';
import { isKean, isZhongZheng } from '../../../utils/utils';
const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 12 },
}
class EditModal extends PureComponent<any, any> {
    constructor(props: any) {
        super(props)
        this.state = {
            id_number: '',
            name: '',
            password: '',
            confirmPassword: '',
            type: '',//级别
            student_type: '',//部门
            sexy: '',
            duty: '',//职务
            loading: false,
            changed_lessons: [],
            exam_date: '',
            company: '',
            invoice: '',
            invoice_img: [],
            previewImg: '',
            previewVisible: false
        }
    }
    changeValue = (e: any, name: string) => {
        this.props.changeValue(e, name)
    }
    changeValueWithTarget = (e: any, name: string) => {
        this.props.changeValueWithTarget(e, name)
    }
    changeFile = (e: any, name: string) => {
        this.props.changeFile(e, name)
    }
    changeLessons = (e: any, d: any) => {
        this.props.changeValue(e, 'lessons')
        this.setState({
            changed_lessons: d.join(`\\`)
        })
    }
    changeExamDate = (e: any, exam_date: string) => {
        this.props.changeValue(exam_date, 'exam_date')
    }
    submitHandle = () => {
        const { id_number,
            name,
            password,
            confirmPassword,
            type,
            student_type,
            sexy,
            duty, phone, currentRow, lessons, integral, exam_date,
            company, currentPage, auditHandle, invoice, invoice_img, idcard, origin_idcard, sort, isUserManagent, month, year } = this.props.data;
        const { hideEditPerson, renderList } = this.props;
        const { changed_lessons } = this.state;
        if (!id_number || !name || !student_type[0]) {
            return message.error('请完善用户信息')
        }
        if ((type + '') === '2' && !lessons[0]) {
            return message.error('请完善用户信息')
        }
        if (password !== confirmPassword) {
            return message.error('两次密码输入不一致')
        }
        this.setState({
            loading: true
        })
        const img = invoice_img[0] ? invoice_img[0].originFileObj ? invoice_img[0].originFileObj : invoice_img[0].name : '';
        const editHandle = () => {
            const { lessons } = this.props.data;
            let save = 0;
            const noChangeSubject = currentRow.subject.includes(lessons.join(','));
            const noChangeIntegral = currentRow.integral * 1 === integral * 1;
            const noChangeIdNumber = currentRow.id_number === id_number;
            if (isUserManagent) {
                if (!noChangeSubject && noChangeIntegral && noChangeIdNumber) {
                    save = 1  /*科目 */
                } else if (!noChangeIntegral && noChangeSubject && noChangeIdNumber) {
                    save = 2  /* 积分 */
                } else if (!noChangeSubject && !noChangeIntegral && noChangeIdNumber) {
                    save = 3  /* 科目,积分 */
                } else if (!noChangeIdNumber && noChangeSubject && noChangeIntegral) {
                    save = 4/* 身份证 */
                } else if (!noChangeIdNumber && !noChangeIntegral && noChangeSubject) {
                    save = 5 /* 身份证、积分 */
                } else if (!noChangeIdNumber && !noChangeSubject && noChangeIntegral) {
                    save = 6 /* 身份证、科目 */
                } else if (!noChangeIdNumber && !noChangeSubject && !noChangeIntegral) {
                    save = 7 /* 身份证、科目 、积分*/
                } else {
                    save = 0
                }
            }
            editPerson({
                id_number, name, password, type, student_type, idcard,
                sexy, duty, phone, id: currentRow.id, company, subject: lessons,
                integral, exam_date, invoice, invoice_img: invoice_img[0] ? img : '', month, year
            }).then(res => {
                this.setState({
                    loading: false
                })
                if (res.status === 1) {
                    message.success('修改成功')
                    if (auditHandle && !isAnte()) {
                        Modal.confirm({
                            okText: '确定',
                            cancelText: '取消',
                            title: '提示',
                            content: '确定审核选中的用户？',
                            onOk: () => {
                                const student_type = JSON.parse(localStorage.getItem('userinfo') || '{}').student_type;
                                auditPerson({ id: currentRow.id, student_type, uid: currentRow.id }).then(res => {
                                    if (res.status === 1) {
                                        message.success('已审核')
                                        renderList(currentPage, sort)
                                        const name = localStorage.getItem('name')
                                        const operation = name + '审核了' + 1 + '名学员'
                                        getHandle({ operation })
                                    } else {
                                        message.error('审核失败')
                                    }
                                })
                            }
                        })
                    }
                    hideEditPerson()
                    const adminname = localStorage.getItem('name')
                    const operation = adminname + '修改了' + name + '的学员信息'
                    if (save > 0 || currentRow.subject !== lessons.join(',')) {
                        upSubjectMember({ phone, id_number, name, type, student_type, subject: lessons, save }).then(res => {
                            renderList(currentPage, sort)
                        })
                    } else {
                        renderList(currentPage, sort)
                    }
                    if (currentRow.subject !== lessons.join(',')) {
                        const operation = adminname + '修改了' + name + '的学科，由(' + currentRow.subjects + ') 改为 (' + changed_lessons + ')'
                        getHandle({ operation })
                    }
                    getHandle({ operation })

                } else {
                    message.error('修改失败')
                }
            })

        }
        if (isZhongZheng()) {
            checkRepeatIdCard({ idcard }).then(res => {
                if (idcard && Number(idcard) !== Number(idcard)) return message.error('编号只能输入数字')
                if (idcard && Number(idcard) <= 0) return message.error('请输入有效编号')
                if (idcard && Number(idcard) !== Number(origin_idcard) && res.status === 2) {
                    return message.error('有重复的编号')
                }
                editHandle()

            })
        } else {
            editHandle()
        }


    }
    preViewImage = (e: any) => {
        this.setState({
            previewImg: e.url,
            previewVisible: true
        })
    }
    hidePreviewImg = () => {
        this.setState({
            previewVisible: false
        })
    }
    render() {
        const { editVisible, options, id_number,
            name,
            password,
            confirmPassword,
            type,
            student_type,
            sexy,
            phone, lessons, lessonsData, typeList, integral,
            loading, currentRow, exam_date, company, invoice, invoice_img,
            idcard, isUserManagement, isPayUsers,year,month
        } = this.props.data;
        const { hideEditPerson } = this.props;
        const { previewVisible, previewImg } = this.state;
        const authority = localStorage.getItem('antd-pro-authority').includes('109') || localStorage.getItem('antd-pro-authority').includes('909');
        const userinfo = JSON.parse(localStorage.getItem('userinfo'))
        return (
            <React.Fragment>
                <Modal confirmLoading={loading} visible={editVisible} onOk={this.submitHandle} onCancel={() => hideEditPerson()} title={<span>修改用户<span style={{ color: "red", fontSize: 14 }}>( 注：带*号的为必填项目，准考证号不能重复新增，否则输入无效！)</span></span>}>
                    <Row>
                        <Col span={24}>
                            <Form>
                                <Form.Item required {...layout} label="准考证号">
                                    <Input placeholder="请输入准考证号" onChange={(e: any) => this.changeValueWithTarget(e, 'id_number')} readOnly={userinfo.super === 1 ? false : true} value={id_number} />
                                </Form.Item>
                                {
                                    isZhongZheng() && isUserManagement ? <Form.Item required {...layout} label="编号">
                                        <Input disabled={userinfo.super} placeholder="请输入编号" onChange={(e: any) => this.changeValueWithTarget(e, 'idcard')} value={idcard} />
                                    </Form.Item> : null
                                }

                                <Form.Item required {...layout} label="用户姓名">
                                    <Input placeholder="请输入用户姓名" onChange={(e: any) => this.changeValueWithTarget(e, 'name')} value={name} />
                                </Form.Item>
                                <Form.Item required {...layout} label="单位部门">
                                    <Cascader placeholder="请选择单位部门" changeOnSelect options={options} value={student_type} onChange={(e) => this.changeValue(e, 'student_type')} />
                                </Form.Item>
                                <Form.Item  {...layout} label="登录密码">
                                    <Input placeholder="请输入登录密码" value={password} onChange={(e) => this.changeValueWithTarget(e, 'password')} />
                                </Form.Item>
                                <Form.Item  {...layout} label="确认密码">
                                    <Input placeholder="请确认密码" onChange={(e) => this.changeValueWithTarget(e, 'confirmPassword')} value={confirmPassword} />
                                </Form.Item>
                                <Form.Item  {...layout} label="培训科目" required>
                                    <TreeSelect
                                        treeData={lessonsData}
                                        onChange={this.changeLessons}
                                        value={lessons}
                                        allowClear
                                        multiple
                                        // treeCheckable
                                        showSearch
                                        placeholder="请选择培训科目"
                                    />
                                </Form.Item>
                                <Form.Item  {...layout} label="联系电话">
                                    <InputNumber style={{ width: '100%' }} onChange={(e) => this.changeValue(e, 'phone')} value={phone || null} placeholder="请输入联系电话"></InputNumber>
                                </Form.Item>

                                <Form.Item  {...layout} label="性别">
                                    <Select placeholder="请选择性别" onChange={(e) => this.changeValue(e, 'sexy')} value={sexy}>
                                        <Select.Option value="3">保密</Select.Option>
                                        <Select.Option value="1">男</Select.Option>
                                        <Select.Option value="2">女</Select.Option>
                                    </Select>
                                </Form.Item>
                                {/* <Form.Item  {...layout} label="职务">
                                <Select placeholder="请选择职务" onChange={this.changeDuty} value={duty}>
                                    {
                                        positionData.map(item => {
                                            return <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                                        })
                                    }
                                </Select>
                            </Form.Item> */}
                                {
                                    hasCompany() && <Form.Item  {...layout} label="公司名称">
                                        <Input onChange={(e) => this.changeValueWithTarget(e, 'company')} value={company} placeholder="请输入公司名称"></Input>
                                    </Form.Item>
                                }
                                {
                                    isZhengda() && <Form.Item  {...layout} label="考试时间">
                                        <DatePicker style={{ width: '100%' }} value={exam_date && moment(exam_date, "YYYY-MM-DD")} format="YYYY-MM-DD" onChange={this.changeExamDate} />
                                    </Form.Item>
                                }
                                {
                                    (isAnte() || isZhongZheng()) && <Form.Item  {...layout} label={isPayUsers ? "缴费编号" : "发票编号"}>
                                        <Input placeholder={isPayUsers ? "请输入缴费编号" : "请输入发票编号"} value={invoice} onChange={(e) => this.changeValueWithTarget(e, 'invoice')} />
                                    </Form.Item>
                                }
                                {/* {
                                    isAnte() && <Form.Item  {...layout} label="发票图片">
                                        <Upload onPreview={this.preViewImage} beforeUpload={() => { return false }} onChange={(e) => this.changeFile(e, 'invoice_img')} fileList={invoice_img}><Button>上传图片</Button></Upload>
                                    </Form.Item>
                                } */}
                                <Form.Item  {...layout} label="级别">
                                    {
                                        authority ? <Select placeholder="请选择级别" onChange={(e) => this.changeValue(e, 'type')} value={Number(type) === Number(type) ? type : 2}>
                                            <Select.Option value={2} key={2}>考生</Select.Option>
                                            {
                                                typeList.map((item: any) => {
                                                    return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                                })
                                            }
                                        </Select>
                                            : <Select placeholder="请选择级别" disabled value={type}>
                                                <Select.Option value={2} key={2}>考生</Select.Option>
                                                {
                                                    typeList.map((item: any) => {
                                                        return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                                    })
                                                }
                                            </Select>
                                    }
                                </Form.Item>
                                {
                                    (isKean()) && <Form.Item  {...layout} label="往年培训时间">
                                        <InputNumber value={Number(year)} placeholder="年" onChange={(e) => this.changeValue(e, 'year')} />年
                                           <InputNumber value={Number(month)} placeholder="月" onChange={(e) => this.changeValue(e, 'month')} />月
                                        </Form.Item>
                                }
                                <Authorized authority={[111, 911]}>
                                    <Form.Item  {...layout} label="积分">
                                        <Input placeholder="请输入积分" onChange={(e) => this.changeValueWithTarget(e, 'integral')} value={(integral === 'null' || !integral) ? '' : integral} />
                                    </Form.Item>
                                </Authorized>

                                {/* <Form.Item {...layout} label="学历">
                                <Select placeholder="请选择学历" >
                                    <Select.Option value="博士">博士</Select.Option>
                                    <Select.Option value="硕士">硕士</Select.Option>
                                    <Select.Option value="本科">本科</Select.Option>
                                    <Select.Option value="专科">专科</Select.Option>
                                    <Select.Option value="中专">中专</Select.Option>
                                    <Select.Option value="高中">高中</Select.Option>
                                    <Select.Option value="初中">初中</Select.Option>
                                    <Select.Option value="小学">小学</Select.Option>
                                    <Select.Option value="其它">其它</Select.Option>
                                </Select>
                            </Form.Item>
                            <Form.Item {...layout} label="工作时间"><DatePicker placeholder="请输入工作时间" style={{ width: '100%' }} /></Form.Item> */}
                            </Form>
                        </Col>
                        {/* <Col span={12}>
                        <Form>
                            <Form.Item {...layout} label="所属岗位">
                                <Select placeholder="请选择所属岗位" >
                                </Select>
                            </Form.Item>
                            <Form.Item {...layout} label="所属角色">
                                <Select placeholder="请选择所属角色" >
                                </Select>
                            </Form.Item>
                            <Form.Item {...layout} label="准考证号">
                                <Input placeholder="请输入准考证号" />
                                <Button style={{ marginTop: 10 }} type="primary">检查重复</Button>
                            </Form.Item>
                            <Form.Item {...layout} label="照片" help="建议尺寸 宽82*高119">
                                <Upload onChange={this.changeImage} beforeUpload={()=>{return false}} fileList={fileList} accept=".png,.jpg" multiple><Button>上传照片</Button></Upload>
                            </Form.Item>
                            <Form.Item {...layout} label="部门"><Input placeholder="请输入部门" /></Form.Item>
                            <Form.Item {...layout} label="职务"><Input placeholder="请输入职务" /></Form.Item>
                            <Form.Item {...layout} label="手机号"><Input placeholder="请输入手机号" /></Form.Item>
                            <Form.Item {...layout} label="级别"><Input placeholder="请输入级别" /></Form.Item>
                        </Form>
                    </Col> */}
                    </Row>

                </Modal>
                <Modal width={'50vw'} footer={null} onCancel={this.hidePreviewImg} visible={previewVisible}>
                    <img onClick={() => window.open(previewImg)} style={{ width: '100%', cursor: 'pointer' }} src={previewImg} alt="" />
                </Modal>
            </React.Fragment>
        );
    }
}

export default EditModal;
